package com.hsmw.api.controller.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.vo.HomeVolume;
import com.hsmw.api.vo.ManageVehicleListVo;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.form.GetObjectByIdForm;
import com.hsmw.domain.form.GetVehiclePageByLeasingCompanyIdForm;
import com.hsmw.common.base.BaseController;
import com.hsmw.common.base.BasePage;
import com.htn.common.core.base.DataResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WD
 */
@Api(tags = "BIZ-租赁公司表")
@RestController
@RequestMapping("/api/biz/leasingCompany")
public class BizLeasingCompanyController extends BaseController<HsmwLeasingCompanyService, HsmwLeasingCompany> {

	@Autowired
	private HsmwLeasingCompanyService hsmwLeasingCompanyService;
	@Autowired
	private HsmwVehicleService hsmwVehicleService;
	@Autowired
	private HsmwVehicleMapper hsmwVehicleMapper;

	@Autowired
	private HsmwUserDriverMapper hsmwUserDriverMapper;

	@Autowired
	private HsmwOrderVehicleRelationMapper hsmwOrderVehicleRelationMapper;






	@Autowired
	private HsmwPmUserService hsmwPmUserService;

	@Autowired
	private HsmwConcreteUserService hsmwConcreteUserService;

	@Autowired
	private HsmwDriverUserService hsmwDriverUserService;

	@Autowired
	private HsmwBizUserService hsmwBizUserService;

	@Autowired
	private HsmwHtnUserService hsmwHtnUserService;

	@Autowired
	private HsmwTpspUserService hsmwTpspUserService;

	@Autowired
	private HsmwSaleUserService hsmwSaleUserService;


	@Autowired
	private HsmwPmUserMapper hsmwPmUserMapper;

	@Autowired
	private HsmwConcreteUserMapper hsmwConcreteUserMapper;

	@Autowired
	private HsmwDriverUserMapper hsmwDriverUserMapper;

	@Autowired
	private HsmwBizUserMapper hsmwBizUserMapper;

	@Autowired
	private HsmwHtnUserMapper hsmwHtnUserMapper;

	@Autowired
	private HsmwTpspUserMapper hsmwTpspUserMapper;

	@Autowired
	private HsmwSaleUserMapper hsmwSaleUserMapper;


	/**
	 * 分页
	 *
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "获取租赁公司分页列表", notes = "获取租赁公司分页列表", produces = "application/json")
	@PostMapping("/getLeasingCompanyPage")
	public DataResponse getLeasingCompanyPage(@RequestBody @Valid BasePage<HsmwLeasingCompany> basePage) {
		IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
		HsmwLeasingCompany hsmwLeasingCompany = basePage.getRequestData();
		IPage<HsmwLeasingCompany> data = hsmwLeasingCompanyService.getLeasingCompanyPage(page, hsmwLeasingCompany);
		if (CollectionUtil.isNotEmpty(data.getRecords())) {
			List<String> leasingCompanyIdList = data.getRecords().stream().map(HsmwLeasingCompany::getId).collect(Collectors.toList());
			List<HsmwVehicle> hsmwVehicleList = hsmwVehicleMapper.selectList(Wrappers.lambdaQuery(HsmwVehicle.class).in(HsmwVehicle::getLeasingCompanyId, leasingCompanyIdList));
			Map<String, List<HsmwVehicle>> listMap = hsmwVehicleList.stream().collect(Collectors.groupingBy(HsmwVehicle::getLeasingCompanyId));
			data.getRecords().forEach(hsmwLeasingCompany1 -> {
				Integer sumCount = 0;
				Double sumVolume = 0.0;
				Double doubleVolume = hsmwOrderVehicleRelationMapper.findSumVolumeByLeasing(hsmwLeasingCompany1.getId());
				sumVolume += doubleVolume;
				if (listMap.get(hsmwLeasingCompany1.getId()) != null) {
					hsmwLeasingCompany1.setVehicleCount(listMap.get(hsmwLeasingCompany1.getId()).size());
					List<HsmwVehicle> hsmwVehicles = listMap.get(hsmwLeasingCompany1.getId());
					for (HsmwVehicle hsmwVehicle : hsmwVehicles) {
						Integer count = hsmwUserDriverMapper.selectCount(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, hsmwVehicle.getId()));
						sumCount += count;
					}
				}
				hsmwLeasingCompany1.setDriverCount(sumCount);
				hsmwLeasingCompany1.setSumVolume(String.format("%.1f",sumVolume));
			});
		}
		return new DataResponse(data);
	}

	/**
	 * 获取租赁公司下拉列表
	 */
	@ApiOperation(value = "获取租赁公司下拉列表", notes = "获取租赁公司下拉列表", produces = "application/json")
	@PostMapping("/getLeasingCompanySelect")
	public DataResponse getLeasingCompanySelect() {
		List<HsmwLeasingCompany> data = hsmwLeasingCompanyService.getLeasingCompanySelect();
		return new DataResponse(data);
	}

	/**
	 * 根据ID查询数据
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "根据id查询数据", notes = "根据id查询数据", produces = "application/json")
	@PostMapping("/getLeasingCompanyById")
	public DataResponse getLeasingCompanyById(@RequestBody GetObjectByIdForm form) {
		Map map = hsmwLeasingCompanyService.getLeasingCompanyById(form.getKey(), form.getMonth(),form.getDriverVolume());
		return new DataResponse(map);
	}

	/**
	 * 新增
	 * 修改  必须带ID
	 *
	 * @param hsmwLeasingCompany
	 * @return
	 */
	@ApiOperation(value = "新增/修改", notes = "新增：传对象；修改：传id；", produces = "application/json")
	@PostMapping("/saveOrUpdateLeasingCompany")
	public DataResponse saveOrUpdateLeasingCompany(@RequestBody @Valid HsmwLeasingCompany hsmwLeasingCompany) {

		if(hsmwLeasingCompany ==null){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"参数传递错误");
		}
		if(StringUtils.isNotBlank(hsmwLeasingCompany.getName())){
			List<HsmwLeasingCompany> list = hsmwLeasingCompanyService.list(new LambdaQueryWrapper<HsmwLeasingCompany>()
					.eq(HsmwLeasingCompany::getName, hsmwLeasingCompany.getName())
					.ne(HsmwLeasingCompany::getId,hsmwLeasingCompany.getId()));
			if(CollectionUtil.isNotEmpty(list)){
				return new DataResponse(CommonConstants.ResponseStatus.FAIL,"名称重复");
			}
		}

		if(StringUtils.isNotBlank(hsmwLeasingCompany.getTel())){
			List<HsmwLeasingCompany> list = hsmwLeasingCompanyService.list(new LambdaQueryWrapper<HsmwLeasingCompany>()
					.eq(HsmwLeasingCompany::getTel, hsmwLeasingCompany.getTel())
					.ne(HsmwLeasingCompany::getId,hsmwLeasingCompany.getId()));
			if(CollectionUtil.isNotEmpty(list)){
				return new DataResponse(CommonConstants.ResponseStatus.FAIL,"手机号重复");
			}
			List<HsmwHtnUser> users =hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
					.eq(HsmwHtnUser::getUsername,hsmwLeasingCompany.getTel()));
			if(CollectionUtil.isNotEmpty(users)){
				return new DataResponse(CommonConstants.ResponseStatus.FAIL,"您输入的负责人电话，在系统已存在");
			}
		}

		return new DataResponse(hsmwLeasingCompanyService.saveOrUpdateLeasingCompany(hsmwLeasingCompany));
	}

	/**
	 * 获取租赁公司下的车辆列表
	 *
	 * @see BizVehicleController#getVehiclePage
	 */
	@ApiOperation(value = "获取租赁公司下的车辆列表", notes = "获取租赁公司下的车辆列表", produces = "application/json")
	@PostMapping("/getVehiclePage")
	public DataResponse getVehiclePage(@RequestBody @Valid BasePage<HsmwVehicle> basePage) {
		IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
		HsmwVehicle hsmwVehicle = basePage.getRequestData();
		IPage<HsmwVehicle> data = hsmwVehicleService.getVehiclePage(page, hsmwVehicle);
		return new DataResponse(data);
	}


	/**
	 * 管理车辆列表
	 */
	@ApiOperation(value = "管理车辆列表", notes = "管理车辆列表  key：租赁公司id", produces = "application/json")
	@PostMapping("/getManageVehicleList")
	public DataResponse getManageVehicleList(@RequestBody @Valid GetObjectByIdForm form) {
		ManageVehicleListVo result = hsmwVehicleService.getManageVehicleList(form.getKey());
		return new DataResponse(result);
	}

	/**
	 * 修改租赁公司的车辆
	 *
	 * @param jsonObject
	 * @return
	 */
	@ApiOperation(value = "修改租赁公司的车辆", notes = "修改租赁公司的车辆  leasingCompanyId  vehicleIdStr", produces = "application/json")
	@PostMapping("/updateLeasingCompanyVehicle")
	public DataResponse updateLeasingCompanyVehicle(@RequestBody JSONObject jsonObject) {
		hsmwLeasingCompanyService.updateLeasingCompanyVehicle(jsonObject.getStr("leasingCompanyId"), jsonObject.getStr("vehicleIdStr"));
		return new DataResponse(true);
	}


	@ApiOperation(value = "月统计方量", notes = "月统计方", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id",value = "租赁公司Id",dataType = "String"),
			@ApiImplicitParam(name = "month",value = "月份",dataType = "String")
	})
	@PostMapping("/findVehicleVolumeByMonth")
	public DataResponse findVehicleVolumeByMonth(String id,String month) {
		Map map = new HashMap();

		StringBuffer stringBuffer = new StringBuffer(month);
		StringBuffer append = stringBuffer.append("-01");
		String s = LocalDate.now().toString();
		String[] split = s.split("-");
		String s1 = split[0];
		StringBuffer buffer = new StringBuffer(s1+"-");
		StringBuffer date = buffer.append(append);
		String s2 = date.toString();
		LocalDate localDate = LocalDate.parse(s2, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		//这个月的第一天
		Date monthStart = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
		//这个月的最后一天 下个月的第一天
		Date monthEnd = Date.from(localDate.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
		DateTime endTime = DateUtil.date(monthEnd);
		DateTime startTime = DateUtil.date(monthStart);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(endTime);
		calendar.add(Calendar.DATE,-1);
		Date dateEndtime =calendar.getTime();
		List<HomeVolume> homeVolumes = hsmwLeasingCompanyService.findVehicleVolumeByMonth(id,month);
		List<String> dayBetween = com.htn.common.core.utils.DateUtil.getDayBetween(DateUtil.format(startTime.toJdkDate(), "yyyy-MM-dd"), DateUtil.format(dateEndtime, "yyyy-MM-dd"));
		map.put("homeVolumes",homeVolumes);
		map.put("dayBetween",dayBetween);
		return new DataResponse(map);
	}

	@ApiOperation(value = "饼状图项目统计方量", notes = "饼状图项目统计方量", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id",value = "租赁公司Id",dataType = "String"),
			@ApiImplicitParam(name = "month",value = "月份",dataType = "String")
	})
	@PostMapping("/findItemVolumeByMonth")
	public DataResponse findItemVolumeByMonth(String id,String month){

		List<HomeVolume> homeVolumes = hsmwLeasingCompanyService.findItemVolumeByMonth(id,month);
		return new DataResponse(homeVolumes);
	}


	/**
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "删除公司信息", notes = "删除公司信息", produces = "application/json")
	@PostMapping("/deleteLeasingCompanyById")
	public DataResponse deleteLeasingCompanyById(@RequestBody GetObjectByIdForm form){

		if(form.getKey() == null){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"id不能为空");
		}
		boolean del = hsmwLeasingCompanyService.removeById(form.getKey());
		if(del){
			return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,"删除成功");
		}
		return new DataResponse(CommonConstants.ResponseStatus.FAIL,"删除失败");

	}


	@ApiOperation(value = "导出信息", notes = "导出信息", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id",value = "公司id",dataType = "String"),
			@ApiImplicitParam(name = "startTime",value = "开始时间",dataType = "String"),
			@ApiImplicitParam(name = "endTime",value = "结束时间",dataType = "String")
	})
	@PostMapping("/findOrderBalanceByTime")
	public DataResponse findOrderBalanceByTime(String startTime,String endTime,String id) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date sTime = sdf.parse(startTime);
		Date eTime = sdf.parse(endTime);
		if(eTime.before(sTime)){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"结束时间不能小于开始时间");
		}

		return hsmwLeasingCompanyService.findOrderBalanceByTime(startTime,endTime,id);
	}

	@ApiOperation(value = "编辑，确认导出信息", notes = "编辑导出信息", produces = "application/json")
	@PostMapping("/updateOrderBalance")
	public DataResponse updateOrderBalance(@RequestBody HsmwOrderBalance hsmwOrderBalance){


		return hsmwLeasingCompanyService.updateOrderBalance(hsmwOrderBalance);
	}


	@ApiOperation(value = "确认", notes = "确认", produces = "application/json")
	@PostMapping("/updateOrderBalances")
	public DataResponse updateOrderBalances(@RequestBody HsmwOrderBalance hsmwOrderBalance){


		return hsmwLeasingCompanyService.updateOrderBalances(hsmwOrderBalance);
	}

	@ApiOperation(value = "导出信息", notes = "导出信息", produces = "application/json")
	@PostMapping("/insertBalanceOnRecord")
	public DataResponse insertBalanceOnRecord(){


		return hsmwLeasingCompanyService.insertBalanceOnRecord();
	}

}
